package ee.emhi;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Linnad extends ListActivity {
		
	ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
	ArrayList<String> favorites = new ArrayList<String>();
	ProgressDialog dialog;
	EventDataSQLHelper eventsData;
	static String warnings = "";
	final Context context = Linnad.this;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.linnad);

		// for SQLight
		eventsData = new EventDataSQLHelper(this);

		// dialog = ProgressDialog.show(Linnad.this, "",
		// "Andmeid laetakse. \nPalun oota...", true);

		// thread for downloading xml from web
		// new DownloadFilesTask().execute();
		worker(Splashscreen.citys);

	}

	// subclass for downloading xml from web
	@SuppressWarnings("unused")
	/*private class DownloadFilesTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			warnings = XMLfunctions
					.getXML("http://www.emhi.ee/ilma_andmed/xml/hoiatus.php");
			String xml = XMLfunctions
					.getXML("http://www.emhi.ee/ilma_andmed/xml/observations.php");

			return xml;
		}
	}

		protected void onPostExecute(String result) {
			dialog.dismiss();
			if(Splashscreen.warnings.length()>50){
				Log.d("DATACHECK 3", "HAS WARNINGS!");
				hasWarningsPopup();
			}
			worker(result);
		}		
	}
	*/

	public void worker(String xml) {
		makeDataList(xml);
		setToListView();
	}

	// method for taking raw xml and turning it to form that we want - listview
	// elements
	public void makeDataList(String xml) {
		Log.d("DATACHECK 1", xml);
		
		time(xml);
		
		// xml to Document
		Document doc = XMLfunctions.XMLfromString(xml);

		// get all the required nodes
		NodeList nodes = doc.getElementsByTagName("station");

		// map data and add to list
		for (int i = 0; i < nodes.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();

			Element e = (Element) nodes.item(i);
			String linn = XMLfunctions.getValue(e, "name");
			String temp = XMLfunctions.getValue(e, "airtemperature");
			String tuul = XMLfunctions.getValue(e, "windspeed");
			String sademed = XMLfunctions.getValue(e, "precipitations");

			// Controlling that no empty data is sent to screen
			// (this can happen if XML is not fully upgraded (some spaces are
			// left empty)
			if (temp.equals("")) {
				map.put("name", linn);
				map.put("temp", "Andmed hetkel puuduvad");
				map.put("favorite", "false");
				map.put("id", i + "");
			} else {
				// Adding to map
				map.put("name", linn);
				map.put("temp", "Temperatuur: " + temp + "\u00B0" + "C");
				map.put("tuul", "Tuule kiirus: " + tuul);
				map.put("sademed", "Sademed: " + sademed);
				map.put("favorite", "false");
				map.put("id", i + "");
			}
			// Adding to list
			mylist.add(map);
		}
		Log.d("DATACHECK 2", mylist.size() + "");
	}

	public void time(String xml){
		
    	int startingplace = Splashscreen.citys.indexOf("stamp=\"") + 7;
    	int endingplace = Splashscreen.citys.indexOf("\">");
    	
    	String date1 = Splashscreen.citys.substring(startingplace, endingplace);
    	long dv = Long.valueOf(date1)*1000;// its need to be in milisecond
    	Date df = new java.util.Date(dv);
    	String vv = new SimpleDateFormat("MM.dd.yyyy HH:mm").format(df);
    	
    	TextView tv = (TextView) findViewById(R.id.time);
    	tv.setText("Viimati uuendatud: "+vv);
    	Log.d("TIMEEEEE", vv);
	}
	
	
	public void setToListView() {
		refreshList();

		final ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@SuppressWarnings("unchecked")
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				final HashMap<String, String> clicked = (HashMap<String, String>) lv
						.getItemAtPosition(position);
			
				showPopup(clicked);
				return false;
			}
		});
	}

	public void showPopup(HashMap<String, String> clicked) {
		if (clicked.get("favorite").equals("false")) {
			addToFavoritesPopup(clicked.get("name"));

		} else if (clicked.get("favorite").equals("1")) {
			removeFromFavoritesPopup(clicked.get("name"));
		}
	}

	public void addToFavoritesPopup(final String name) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage("Lisan lemmikutesse?")
				.setPositiveButton("Jah",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								addFavorite(name);
								refreshList();
							}
						})
				.setNegativeButton("Ei", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog
					}
				});

		AlertDialog alertDialog = builder.create();

		// show it
		alertDialog.show();
	}

	public void removeFromFavoritesPopup(final String name) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage("Eemaldan Lemmikutest?")
				.setPositiveButton("Jah",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								deleteFromFavorites(name);
								returnToPlace(name);
								refreshList();

							}
						})
				.setNegativeButton("Ei", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog
					}
				});

		AlertDialog alertDialog = builder.create();

		// show it
		alertDialog.show();
	}

	public void refreshList() {

		Cursor cursor = getEvents();
		cursor.moveToFirst();
		Log.d("CURSOR", cursor.getCount() + "");
		for (int i = 0; i < mylist.size(); i++) {
			if (cursor.moveToFirst() == true) {
				if (mylist.get(i).get("name")
						.equalsIgnoreCase(cursor.getString(1))) {
					HashMap<String, String> map = mylist.remove(i);
					// HashMap<String, String> mapNew;
					map.put("favorite", "1");
					mylist.add(0, map);
				}
			}

			while (cursor.moveToNext()) {
				Log.d("CURSORrrrrrrrrrrr", cursor.getString(1) + "=="
						+ mylist.get(i).get("name") + "    "
						+ mylist.get(i).get("favorite"));
				if (mylist.get(i).get("name")
						.equalsIgnoreCase(cursor.getString(1))) {
					HashMap<String, String> map = mylist.remove(i);
					// HashMap<String, String> mapNew;
					map.put("favorite", "1");
					mylist.add(0, map);
				}
			}
			cursor.moveToFirst();
		}

		ListAdapter adapter = new SimpleAdapter(Linnad.this, mylist,
				R.layout.linn,
				new String[] { "name", "temp", "tuul", "sademed" }, new int[] {
						R.id.linn, R.id.temperatuur, R.id.tuul, R.id.sademed });

		setListAdapter(adapter);
	}

	public int addFavorite(String name) {
		SQLiteDatabase db = eventsData.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(EventDataSQLHelper.FAVORITES, name); // Contact Name

		// Inserting Row
		db.insert(EventDataSQLHelper.TABLE, null, values);
		//db.close(); // Closing database connection
		return 1;
	}

	private Cursor getEvents() {
		SQLiteDatabase db = eventsData.getReadableDatabase();
		Cursor cursor = db.query(EventDataSQLHelper.TABLE, null, null, null,
				null, null, EventDataSQLHelper.FAVORITES);
		//db.close();
		return cursor;
	}

	public int deleteFromFavorites(String name) {
		SQLiteDatabase db = eventsData.getReadableDatabase();
		db.delete(EventDataSQLHelper.TABLE, "Favorites=\"" + name + "\"", null);
		//db.close();
		return 1;
	}

	public void returnToPlace(String name) {
		for (int i = 0; i < mylist.size(); i++) {
			if (mylist.get(i).get("name").equals(name)) {
				HashMap<String, String> map = mylist.remove(i);
				// HashMap<String, String> mapNew;
				map.put("favorite", "0");
				mylist.add(Integer.parseInt(map.get("id")), map);

				Log.d("Lemmikutest eemaldatakse ", name
						+ " ja pannakse positsioonile " + (map.get("id")));
			}

		}
	}

}
